package com.peng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.peng.dao.mapper.SysUserMapper;
import com.peng.dao.pojo.SysUser;
import com.peng.service.LoginService;
import com.peng.service.SysUserService;
import com.peng.vo.ErrorCode;
import com.peng.vo.LoginUserVo;
import com.peng.vo.Result;
import com.peng.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private LoginService loginService;

    @Override
    public SysUser findUserById(Long id) {
        SysUser sysUser = sysUserMapper.selectById(id);
        if (sysUser==null){
            sysUser=new SysUser();
            sysUser.setNickname("chihiro");
        }
        return sysUser;
    }

    @Override
    public UserVo findUserVoById(Long id) {
        SysUser sysUser = sysUserMapper.selectById(id);
        if (sysUser==null){
            sysUser=new SysUser();
            sysUser.setId(1L);
            sysUser.setAvatar("/static/img/logo.b3a48c0.png");
            sysUser.setNickname("chihiro");
        }
        UserVo userVo = new UserVo();
        userVo.setAvatar(sysUser.getAvatar());
        userVo.setNickName("chihiro");
        userVo.setId(sysUser.getId());
        return userVo;
    }

    @Override
    public SysUser findUser(String account, String md5) {
        LambdaQueryWrapper<SysUser> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getAccount,account)
                   .eq(SysUser::getPassword,md5)
                  .select(SysUser::getAccount ,SysUser::getId,SysUser::getAvatar, SysUser::getNickname)
                .last("limit 1");
        SysUser user = sysUserMapper.selectOne(wrapper);
        return user;
    }

    @Override
    public Result findUserByToken(String token) {
        SysUser user= loginService.findUserByToken(token);
        if (user==null){
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(),ErrorCode.TOKEN_ERROR.getMsg());
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setId(user.getId());
        loginUserVo.setNickname(user.getNickname());
        loginUserVo.setAvatar(user.getAvatar());
        loginUserVo.setAccount(user.getAccount());
        return Result.success(loginUserVo);
    }

    @Override
    public SysUser findAccountUser(String account) {
        LambdaQueryWrapper<SysUser> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getAccount,account);
        wrapper.last("limit 1");
        SysUser user = sysUserMapper.selectOne(wrapper);
        return user;
    }


    @Override
    public void saveUser(SysUser sysUser) {
        sysUserMapper.insert(sysUser);
    }

}
